<?php
// +----------------------------------------------------------------------
// | Scallion 
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.scallion.top All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Liuxg < 420695648@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\Db;

class WxController extends AdminBaseController
{
    /**
     * 微信公众号管理
     */
    public function index()
    {
		$data = db('option')->where(['option_name'=>'wechat_option'])->find();
		if($data){
			$param = json_decode($data['option_value'],true);
		}
		$param['ip'] = gethostbyname($_SERVER['SERVER_NAME']);
		$param['address'] = url('portal/wechatapi/index','','',true);
		$param['callback_address'] = $_SERVER['SERVER_NAME'];
		$this->assign('param',$param);
        return $this->fetch();
    }
	
	public function wx_option_post(){
		if($this->request->param()){
			$is_exist = db('option')->where(['option_name'=>'wechat_option'])->find();
			$param = $this->request->param();
			$data['option_value'] = json_encode($param);
			if($is_exist){
				db('option')->where(['option_name'=>'wechat_option'])->update($data);
				$this->success('保存成功！');
			}
			else{
				$data['autoload'] = 1;
				$data['option_name'] = 'wechat_option';
				db('option')->where(['option_name'=>'wechat_option'])->insert($data);
				$this->success('保存成功！');
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function menu(){
		$menu = $this->getMenu();
		$list = $this->getForeverList();
		$this->assign('list',$list['item']);
		$this->assign('button',json_encode($menu['menu']['button']));
		return $this->fetch();
	}
	
	public function save_menu(){
		if($this->request->param()){
			$param = $this->request->param();
			$menu = $param;
			return $this->setMenu($menu);
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function setMenu($button='-1'){
		$menu = new \wechatcontroller();
		if($button=='-1'){
			$button = [];
			$button['button']['0']['name'] = '扫码';
			$button['button']['0']['type'] = 'scancode_push';
			$button['button']['0']['key'] = 'scallion';
		}
		$res = $menu->menu($menu->options)->createMenu($button);
		return $res;
	}
	
	public function getMenu(){
		$menu = new \wechatcontroller();
		$result = $menu->menu($menu->options)->getMenu();
		return($result);
	}
	
	public function deleteMenu(){
		$menu = new \wechatcontroller();
		$result = $menu->menu($menu->options)->deleteMenu();
		return($result);
	}
	
	public function getForeverList(){
		$list = new \wechatcontroller();
		$result = $list->media($list->options)->getForeverList('news',0,20);
		return $result;
	}
}
